<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警告条 -->
      <el-alert
        class="alert"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类级联选择器 -->
          <el-cascader
            v-model="cateCascaderSelect"
            :options="catelist"
            :props="cateProps"
            @change="cateCascaderSelectChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板区域 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisables"
            @click="addAttriDialogVisible = true"
          >添加参数</el-button>
          <!-- 动态参数表格区域 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe size="mini">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in scope.row.attr_vals"
                  closable
                  class="addElTag"
                  @close="delTagClose(i, scope.row)"
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <!-- 动态参数表格操作按钮 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialogue(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板区域 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisables"
            @click="addAttriDialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性表格区域 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe size="mini">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in scope.row.attr_vals"
                  closable
                  class="addElTag"
                  @close="delTagClose(i, scope.row)
                  "
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <!-- 静态属性表格操作按钮 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialogue(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titileName"
      :visible.sync="addAttriDialogVisible"
      width="50%"
      @close="addAttriDialogClose"
    >
      <el-form ref="addAttriRef" :model="addAttriForm" :rules="addAttrirules" label-width="100px">
        <el-form-item :label="titileName" prop="attr_name">
          <el-input v-model="addAttriForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttriDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isAddAttriFun">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
  </div>
</template>
<script>
export default {
  created() {
    this.getCatelist()
  },
  data() {
    return {
      /* 商品列表 */
      catelist: [],
      /* 选择商品分类级联选择器 的属性Props */
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      /* 选择商品分类级联选择器 的双向绑定到的数组 */
      cateCascaderSelect: [],
      /* tab页签 选中对象 */
      activeName: 'many',
      /* 储存动态参数的数据 */
      manyTableData: [],
      /* 储存静态属性的数据 */
      onlyTableData: [],
      /* 控制添加参数对话框的显示隐藏 */
      addAttriDialogVisible: false,
      /* 添加参数表单对象 */
      addAttriForm: {
        attr_name: ''
      },
      /* 添加参数表单验证规则 */
      addAttrirules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      /* 判断是否使用添加参数函数 */
      isAddAttri: true,
      /* 记录获取返回的属性值 */
      eidtForm: {}
    }
  },
  methods: {
    /* 获取商品列表 */
    async getCatelist() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          pagenum: 1,
          pagesize: 6
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取商品列表失败')
      }
      this.catelist = res.data.result
    },
    /* 监听 选择商品分类级联选择器中 选择框中项发生变化 事件 */
    cateCascaderSelectChange() {
      if (this.cateCascaderSelect.length !== 3) {
        this.cateCascaderSelect = []
      }
      this.getParamsData()
    },
    /* 监听 tab页签 发生改变事件 */
    handleTabClick() {
      this.getParamsData()
    },
    /* 获取参数列表 */
    async getParamsData() {
      /* 选择的商品不是三级商品 */
      if (this.cateCascaderSelect.length !== 3) {
        this.caderSelect = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取参数失败')
        return
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        /* 控制表格中展开行中添加tag标签的显示隐藏 */
        item.inputVisible = false
        /* 双向绑定添加tag标签的添加内容 */
        item.inputValue = ''
      })
      console.log(11111111111, res.data)
      /* 有两类数据，对数据进行分类处理 */
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    /* 监听 添加参数对话框 关闭事件 */
    addAttriDialogClose() {
      this.$refs.addAttriRef.resetFields()
    },
    /* 点击 添加参数对话框 确定按钮, 发送请求 */
    addAttriDialogueConfirm() {
      this.$refs.addAttriRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addAttriForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getParamsData()
        this.addAttriDialogVisible = false
      })
    },
    /* 点击表格中 修改按钮，显示修改对话框 */
    async showEditDialogue(row) {
      this.addAttriDialogVisible = true
      this.isAddAttri = false
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      )

      if (res.meta.status !== 200) {
        this.$message.error('获取信息失败')
      }
      this.eidtForm = res.data
      this.addAttriForm.attr_name = this.eidtForm.attr_name
    },
    /* 点击修改对话框 确定按钮，发送请求 */
    editParams() {
      this.$refs.addAttriRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.eidtForm.attrId}`,
          {
            attr_name: this.addAttriForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改失败')
          return
        }

        this.getParamsData()
        this.$message.success('修改成功')
        this.addAttriDialogVisible = false
      })
    },
    /* 表格中 删除 操作按钮， 发送请求 */
    async delParams(attrid) {
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}}/attributes/${attrid}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getParamsData()
      this.$message.success('删除成功')
      this.addAttriDialogVisible = false
    },
    /* 判断 添加参数对话框_点击确定按钮，使用的添加参数函数还是修改参数函数 */
    isAddAttriFun() {
      if (this.isAddAttri) {
        this.addAttriDialogueConfirm()
      } else {
        this.editParams()
        /* 重置原始值，严防影响以后请求 */
        this.isAddAttri = true
      }
    },
    /* 表格展开行中，监听 点击添加tag标签 的事件 */
    showInput(row) {
      row.inputVisible = true
      /* 让文本框自动获得焦点 */
      /* .$nextTick的作用是当页面上的元素被重新渲染的时候，才会执行回调函数中的代码 */
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /* 表格展开行中， 监听 添加tag标签中enter键抬起或鼠标失去焦点 事件 */
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.inputValue = row.inputValue.trim()
      if (await this.updateParams(row)) {
        row.attr_vals.push(row.inputValue)
      }
      row.inputValue = ''
      // 整个页面都会重新刷新，体验不好
      // this.getParamsData()

      row.inputVisible = false
    },
    /* 表格展开行中， 监听 tag标签关闭（删除tag标签） 事件 */
    async delTagClose(i, row) {
      if (await this.updateParams(row)) {
        row.attr_vals.splice(i, 1)
      }
    },
    /* 发送请求，更新数据 */
    async updateParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.concat(row.inputValue).join(' ')
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('更新数据失败')
        return false
      }
      this.$message.success('更新数据成功')
      return true
    }
  },
  computed: {
    /* 判断 添加参数 按钮是否禁用，禁用返回true， 不禁用返回false */
    isBtnDisables() {
      if (this.cateCascaderSelect.length === 3) {
        return false
      } else {
        return true
      }
    },
    /* 返回选中三级商品的id值 */
    cateId() {
      if (this.cateCascaderSelect.length === 3) {
        return this.cateCascaderSelect[2]
      } else {
        return null
      }
    },
    /* 根据activename返回不同的名称 */
    titileName() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.alert {
  margin-bottom: 18px;
}
.el-cascader {
  margin-left: 6px;
}
.addElTag {
  margin-right: 8px;
}
.input-new-tag {
  width: 120px;
}
</style>
